class Solution {
    int m, n, dx[4] = { 0, 0, 1, -1 }, dy[4] = { 1, -1, 0, 0 };
    vector<vector<int>> memo;
    int dfs(vector<vector<int>> &matrix, int i, int j)
    {
        if(memo[i][j] != 0)
            return memo[i][j];

        // 枚举四个方向
        int path = 1;
        for(int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j])
                path = max(path, dfs(matrix, x, y) + 1);
        }

        memo[i][j] = path;
        return path;
    }
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int ret = 1;    // 可以初始化为0，因为上面的dfs最差就会返回1
        m = matrix.size(), n = matrix[0].size();
        memo = vector<vector<int>>(m, vector<int>(n));
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
                ret = max(ret, dfs(matrix, i, j));
        return ret;
    }
};